import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:math';
import 'dart:async';

// 游戏配置
const int gridSize = 6; // 6x6网格
const double tileSize = 60.0;
const double tileMargin = 4.0;

// 游戏方块类型
enum TileType { red, green, blue, yellow, purple, orange, empty }

// 游戏方块模型
class Tile {
  final int row;
  final int col;
  final TileType type;
  final int id;

  Tile(this.row, this.col, this.type, this.id);

  // 创建空方块
  factory Tile.empty(int row, int col) {
    return Tile(row, col, TileType.empty, -1);
  }
}

// 游戏状态
class GameState {
  List<List<Tile>> grid;
  int score;
  int moves;
  bool isSwapping;
  bool isRemoving;
  bool isFilling;
  bool gameOver;

  GameState()
    : grid = List.generate(
        gridSize,
        (row) => List.generate(gridSize, (col) => Tile.empty(row, col)),
      ),
      score = 0,
      moves = 0,
      isSwapping = false,
      isRemoving = false,
      isFilling = false,
      gameOver = false {
    _initializeGrid();
  }

  // 初始化网格
  void _initializeGrid() {
    int id = 0;
    for (int row = 0; row < gridSize; row++) {
      for (int col = 0; col < gridSize; col++) {
        // 确保不会初始就有可消除的组合
        TileType type;
        do {
          type = TileType.values[Random().nextInt(TileType.values.length - 1)];
        } while (_wouldFormMatch(row, col, type));
        grid[row][col] = Tile(row, col, type, id++);
      }
    }
  }

  // 检查放置一个方块是否会形成可消除的组合
  bool _wouldFormMatch(int row, int col, TileType type) {
    int horizontalCount = 1;
    int verticalCount = 1;

    // 检查水平方向
    for (int c = col - 1; c >= 0 && c >= col - 2; c--) {
      if (grid[row][c].type == type) {
        horizontalCount++;
      } else {
        break;
      }
    }
    if (horizontalCount >= 3) return true;

    // 检查垂直方向
    for (int r = row - 1; r >= 0 && r >= row - 2; r--) {
      if (grid[r][col].type == type) {
        verticalCount++;
      } else {
        break;
      }
    }
    return verticalCount >= 3;
  }

  // 交换两个方块
  void swapTiles(int row1, int col1, int row2, int col2) {
    if (_isAdjacent(row1, col1, row2, col2)) {
      Tile temp = grid[row1][col1];
      grid[row1][col1] = Tile(row1, col1, grid[row2][col2].type, temp.id);
      grid[row2][col2] = Tile(row2, col2, temp.type, grid[row2][col2].id);
      moves++;
    }
  }

  // 检查两个方块是否相邻
  bool _isAdjacent(int row1, int col1, int row2, int col2) {
    return (row1 == row2 && (col1 == col2 - 1 || col1 == col2 + 1)) ||
        (col1 == col2 && (row1 == row2 - 1 || row1 == row2 + 1));
  }

  // 查找所有可消除的方块
  List<Tile> findMatches() {
    List<Tile> matches = [];
    List<List<bool>> marked = List.generate(
      gridSize,
      (_) => List.filled(gridSize, false),
    );

    // 查找水平匹配
    for (int row = 0; row < gridSize; row++) {
      for (int col = 0; col < gridSize - 2; col++) {
        TileType current = grid[row][col].type;
        if (current != TileType.empty &&
            current == grid[row][col + 1].type &&
            current == grid[row][col + 2].type) {
          for (int c = col; c < gridSize && grid[row][c].type == current; c++) {
            if (!marked[row][c]) {
              matches.add(grid[row][c]);
              marked[row][c] = true;
            }
          }
        }
      }
    }

    // 查找垂直匹配
    for (int col = 0; col < gridSize; col++) {
      for (int row = 0; row < gridSize - 2; row++) {
        TileType current = grid[row][col].type;
        if (current != TileType.empty &&
            current == grid[row + 1][col].type &&
            current == grid[row + 2][col].type) {
          for (int r = row; r < gridSize && grid[r][col].type == current; r++) {
            if (!marked[r][col]) {
              matches.add(grid[r][col]);
              marked[r][col] = true;
            }
          }
        }
      }
    }

    return matches;
  }

  // 移除匹配的方块
  void removeMatches(List<Tile> matches) {
    for (Tile tile in matches) {
      grid[tile.row][tile.col] = Tile.empty(tile.row, tile.col);
    }
    score += matches.length * 10;
  }

  // 填充空白方块
  void fillEmptySpaces() {
    int id = gridSize * gridSize;

    // 让方块下落
    for (int col = 0; col < gridSize; col++) {
      for (int row = gridSize - 1; row >= 0; row--) {
        if (grid[row][col].type == TileType.empty) {
          // 找到上方最近的非空方块
          for (int r = row - 1; r >= 0; r--) {
            if (grid[r][col].type != TileType.empty) {
              grid[row][col] = Tile(row, col, grid[r][col].type, id++);
              grid[r][col] = Tile.empty(r, col);
              break;
            }
          }
        }
      }
    }

    // 填充顶部空白
    for (int col = 0; col < gridSize; col++) {
      for (int row = 0; row < gridSize; row++) {
        if (grid[row][col].type == TileType.empty) {
          TileType type;
          do {
            type =
                TileType.values[Random().nextInt(TileType.values.length - 1)];
          } while (_wouldFormMatch(row, col, type));
          grid[row][col] = Tile(row, col, type, id++);
        }
      }
    }
  }

  // 检查是否还有可能的移动
  bool hasPossibleMoves() {
    // 检查所有相邻的方块对，看是否有交换后能形成匹配的可能
    for (int row = 0; row < gridSize; row++) {
      for (int col = 0; col < gridSize; col++) {
        // 尝试向右交换
        if (col < gridSize - 1) {
          // 交换
          Tile temp = grid[row][col];
          grid[row][col] = Tile(row, col, grid[row][col + 1].type, temp.id);
          grid[row][col + 1] = Tile(
            row,
            col + 1,
            temp.type,
            grid[row][col + 1].id,
          );

          // 检查是否有匹配
          bool hasMatch = findMatches().isNotEmpty;

          // 交换回来
          temp = grid[row][col];
          grid[row][col] = Tile(row, col, grid[row][col + 1].type, temp.id);
          grid[row][col + 1] = Tile(
            row,
            col + 1,
            temp.type,
            grid[row][col + 1].id,
          );

          if (hasMatch) return true;
        }

        // 尝试向下交换
        if (row < gridSize - 1) {
          // 交换
          Tile temp = grid[row][col];
          grid[row][col] = Tile(row, col, grid[row + 1][col].type, temp.id);
          grid[row + 1][col] = Tile(
            row + 1,
            col,
            temp.type,
            grid[row + 1][col].id,
          );

          // 检查是否有匹配
          bool hasMatch = findMatches().isNotEmpty;

          // 交换回来
          temp = grid[row][col];
          grid[row][col] = Tile(row, col, grid[row + 1][col].type, temp.id);
          grid[row + 1][col] = Tile(
            row + 1,
            col,
            temp.type,
            grid[row + 1][col].id,
          );

          if (hasMatch) return true;
        }
      }
    }

    return false;
  }
}

// 游戏页面
class MatchGamePage extends StatefulWidget {
  const MatchGamePage({super.key});

  @override
  State<MatchGamePage> createState() => _MatchGamePageState();
}

class _MatchGamePageState extends State<MatchGamePage> {
  // 游戏状态
  late GameState gameState;
  bool gameStarted = false;
  Tile? selectedTile;
  late Timer gameTimer;
  int secondsRemaining = 10; // 90秒游戏时间
  bool hasShownGameOverDialog = false; // 新增：标记对话框是否已弹出

  // 开始游戏
  void _startGame() {
    setState(() {
      gameStarted = true;
      gameState = GameState(); // 初始化游戏状态
    });
    // 启动计时器（仅在游戏开始时启动）
    _startTimer();
    // 处理初始匹配
    _processMatches();
  }

  // 重新开始游戏
  void _restartGame() {
    setState(() {
      gameState = GameState();
      selectedTile = null;
      secondsRemaining = 10;
      hasShownGameOverDialog = false; // 重置弹窗标记
    });
    gameTimer.cancel();
    _startTimer();
    _processMatches();
  }

  // 回到游戏首页
  void _navigateToHome() {
    setState(() {
      gameStarted = false;
      gameState = GameState();
      selectedTile = null;
      secondsRemaining = 10;
      hasShownGameOverDialog = false; // 重置弹窗标记
    });
    gameTimer.cancel();
  }

  // 启动计时器（抽取为单独方法，避免重复代码）
  void _startTimer() {
    gameTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) return; // 防止页面销毁后 setState 报错
      setState(() {
        if (secondsRemaining > 0) {
          secondsRemaining--;
        } else {
          _endGame(); // 时间到，触发游戏结束
          timer.cancel();
        }
      });
    });
  }

  // 游戏结束逻辑
  void _endGame() {
    setState(() {
      gameState.gameOver = true; // 标记游戏结束
    });
    gameTimer.cancel(); // 停止计时器

    // 主动弹出游戏结束对话框（仅在未弹出过且页面未销毁时）
    if (!hasShownGameOverDialog && mounted) {
      setState(() {
        hasShownGameOverDialog = true; // 标记已弹出，避免重复
      });

      showCupertinoDialog(
        context: context,
        barrierDismissible: false, // 禁止点击对话框外部关闭（必须选择按钮）
        builder: (dialogContext) => CupertinoAlertDialog(
          // 对话框标题
          title: const Text(
            '游戏结束',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          // 对话框内容（显示得分）
          content: Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: Text(
              '最终得分：${gameState.score}',
              style: const TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
          ),
          // 对话框按钮（重新开始 + 回到首页）
          actions: [
            // 1. 重新开始按钮
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(dialogContext); // 关闭对话框
                _restartGame(); // 重置游戏
                setState(() {
                  hasShownGameOverDialog = false; // 重置弹窗标记
                });
              },
              child: const Text('重新开始'),
            ),
            // 2. 回到首页按钮
            CupertinoDialogAction(
              onPressed: () {
                Navigator.pop(dialogContext); // 关闭对话框
                _navigateToHome(); // 回到游戏首页
                setState(() {
                  hasShownGameOverDialog = false; // 重置弹窗标记
                });
              },
              child: const Text('回到首页'),
            ),
          ],
        ),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    // 仅初始化游戏状态，不启动计时器（计时器在游戏开始时启动）
    gameState = GameState();
  }

  @override
  void dispose() {
    gameTimer.cancel(); // 页面销毁时停止计时器，防止内存泄漏
    super.dispose();
  }

  // 处理方块点击
  void _onTileTap(int row, int col) {
    if (gameState.isSwapping ||
        gameState.isRemoving ||
        gameState.isFilling ||
        gameState.gameOver) {
      return;
    }

    Tile tappedTile = gameState.grid[row][col];

    if (selectedTile == null) {
      // 第一次选择方块
      selectedTile = tappedTile;
    } else if (selectedTile!.id == tappedTile.id) {
      // 取消选择
      selectedTile = null;
    } else if (gameState._isAdjacent(
      selectedTile!.row,
      selectedTile!.col,
      row,
      col,
    )) {
      // 交换相邻方块
      _swapTiles(selectedTile!.row, selectedTile!.col, row, col);
      selectedTile = null;
    } else {
      // 选择另一个不相邻的方块
      selectedTile = tappedTile;
    }
  }

  // 交换方块并处理匹配
  void _swapTiles(int row1, int col1, int row2, int col2) {
    setState(() {
      gameState.isSwapping = true;
      gameState.swapTiles(row1, col1, row2, col2);
    });

    // 检查交换后是否有匹配
    Future.delayed(const Duration(milliseconds: 300), () {
      if (!mounted) return;
      List<Tile> matches = gameState.findMatches();

      if (matches.isEmpty) {
        // 如果没有匹配，交换回来
        setState(() {
          gameState.swapTiles(row1, col1, row2, col2);
          gameState.isSwapping = false;
        });
      } else {
        // 如果有匹配，处理匹配
        setState(() {
          gameState.isSwapping = false;
        });
        _processMatches();
      }
    });
  }

  // 处理匹配、填充和检查游戏结束
  void _processMatches() async {
    bool hasMatches;

    do {
      if (!mounted) return;
      setState(() {
        gameState.isRemoving = true;
      });

      // 找到并移除匹配的方块
      List<Tile> matches = gameState.findMatches();
      hasMatches = matches.isNotEmpty;

      if (hasMatches) {
        if (!mounted) return;
        setState(() {
          gameState.removeMatches(matches);
        });

        // 等待移除动画
        await Future.delayed(const Duration(milliseconds: 300));

        if (!mounted) return;
        setState(() {
          gameState.isRemoving = false;
          gameState.isFilling = true;
        });

        // 填充空白方块
        if (!mounted) return;
        setState(() {
          gameState.fillEmptySpaces();
        });

        // 等待填充动画
        await Future.delayed(const Duration(milliseconds: 300));

        if (!mounted) return;
        setState(() {
          gameState.isFilling = false;
        });
      } else {
        if (!mounted) return;
        setState(() {
          gameState.isRemoving = false;
        });
      }
    } while (hasMatches);

    // 检查是否还有可能的移动（无移动则游戏结束）
    if (!gameState.hasPossibleMoves() && !gameState.gameOver) {
      if (!mounted) return;
      _endGame(); // 调用游戏结束逻辑
    }
  }

  // 获取方块颜色
  Color _getTileColor(TileType type) {
    switch (type) {
      case TileType.red:
        return CupertinoColors.systemRed;
      case TileType.green:
        return CupertinoColors.systemGreen;
      case TileType.blue:
        return CupertinoColors.systemBlue;
      case TileType.yellow:
        return CupertinoColors.systemYellow;
      case TileType.purple:
        return CupertinoColors.systemPurple;
      case TileType.orange:
        return CupertinoColors.systemOrange;
      case TileType.empty:
        return Colors.transparent;
    }
  }

  // 获取方块图标
  IconData _getTileIcon(TileType type) {
    switch (type) {
      case TileType.red:
        return CupertinoIcons.heart_fill;
      case TileType.green:
        return CupertinoIcons.tree; // 可用的Cupertino图标
      case TileType.blue:
        return CupertinoIcons.drop_fill;
      case TileType.yellow:
        return CupertinoIcons.star_fill;
      case TileType.purple:
        return CupertinoIcons.circle_fill;
      case TileType.orange:
        return CupertinoIcons.sun_min_fill;
      case TileType.empty:
        return CupertinoIcons.clear;
    }
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: const Text('消消乐'),
        backgroundColor: CupertinoTheme.of(context).barBackgroundColor,
      ),
      child: SafeArea(
        child: Container(
          padding: const EdgeInsets.all(16.0),
          child: gameStarted
              ? _buildGameContent(context)
              : _buildStartScreen(context),
        ),
      ),
    );
  }

  // 构建开始游戏界面
  Widget _buildStartScreen(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '消消乐',
            style: CupertinoTheme.of(context).textTheme.navTitleTextStyle
                .copyWith(fontSize: 48, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 32),
          Text(
            '匹配三个或更多相同颜色的方块来消除它们',
            style: CupertinoTheme.of(
              context,
            ).textTheme.textStyle.copyWith(fontSize: 18),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 48),
          CupertinoButton.filled(
            onPressed: _startGame,
            child: const Text('开始游戏'),
            padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 12),
            minSize: 60,
            borderRadius: BorderRadius.circular(12),
          ),
          const SizedBox(height: 16),
          CupertinoButton(
            onPressed: () {
              // 显示游戏规则弹窗
              showCupertinoDialog(
                context: context,
                builder: (context) => CupertinoAlertDialog(
                  title: const Text('游戏规则'),
                  content: const Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('1. 点击并交换相邻的方块', textAlign: TextAlign.left),
                      Text('2. 匹配三个或更多相同颜色的方块来消除它们', textAlign: TextAlign.left),
                      Text('3. 消除方块可以获得分数', textAlign: TextAlign.left),
                      Text('4. 时间耗尽或无可用移动时，游戏结束', textAlign: TextAlign.left),
                    ],
                  ),
                  actions: [
                    CupertinoDialogAction(
                      child: const Text('了解了'),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
              );
            },
            child: const Text('游戏规则'),
          ),
        ],
      ),
    );
  }

  // 构建游戏内容
  Widget _buildGameContent(BuildContext context) {
    return Column(
      children: [
        // 1. 游戏信息栏（分数、步数、时间）
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '分数',
                    style: TextStyle(
                      color: CupertinoColors.inactiveGray,
                      fontSize: 14,
                    ),
                  ),
                  Text(
                    '${gameState.score}',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '步数',
                    style: TextStyle(
                      color: CupertinoColors.inactiveGray,
                      fontSize: 14,
                    ),
                  ),
                  Text(
                    '${gameState.moves}',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '时间',
                    style: TextStyle(
                      color: CupertinoColors.inactiveGray,
                      fontSize: 14,
                    ),
                  ),
                  Text(
                    '${secondsRemaining}s',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: secondsRemaining < 30
                          ? CupertinoColors.systemRed
                          : CupertinoColors.black,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),

        // 2. 游戏网格（占满剩余空间）
        Expanded(
          child: Center(
            child: Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                color: CupertinoColors.lightBackgroundGray,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: AspectRatio(
                aspectRatio: 1.0,
                child: GridView.builder(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: gridSize,
                    mainAxisSpacing: tileMargin,
                    crossAxisSpacing: tileMargin,
                  ),
                  itemCount: gridSize * gridSize,
                  itemBuilder: (context, index) {
                    int row = index ~/ gridSize;
                    int col = index % gridSize;
                    Tile tile = gameState.grid[row][col];
                    bool isSelected =
                        selectedTile != null && selectedTile!.id == tile.id;

                    return CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: () => _onTileTap(row, col),
                      child: Container(
                        decoration: BoxDecoration(
                          color: tile.type == TileType.empty
                              ? Colors.transparent
                              : _getTileColor(tile.type),
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: tile.type != TileType.empty
                              ? [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.15),
                                    blurRadius: 4,
                                    offset: const Offset(0, 2),
                                  ),
                                ]
                              : [],
                          border: isSelected
                              ? Border.all(
                                  color: CupertinoColors.systemBlue,
                                  width: 3,
                                )
                              : null,
                        ),
                        child: tile.type != TileType.empty
                            ? Center(
                                child: Icon(
                                  _getTileIcon(tile.type),
                                  color: Colors.white,
                                  size: 32,
                                ),
                              )
                            : null,
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
        ),

        // 3. 游戏结束覆盖层（条件渲染）
      ],
    );
  }
}
